﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Q.Extensions
{
    public static class RandomStringVocabulary
    {
        public static readonly char[] Alphabet;
        public static readonly char[] Digits;
        public static readonly char[] DigitsAndAlphabet;
        public static readonly char[] Hexadecimal;
        public static readonly char[] LowerAlphabet;
        public static readonly char[] UpperAlphabet;

        static RandomStringVocabulary()
        {
            var digits = "0123456789";
            var alpha = "abcdefghijklmnopqrstuvwxyz";
            var hexalpha = "abcdef";

            Digits 
                = digits.ToCharArray();
            Alphabet 
                = (alpha + alpha.ToUpper()).ToCharArray();
            LowerAlphabet 
                = alpha.ToCharArray();
            UpperAlphabet 
                = alpha.ToUpper().ToCharArray();
            Hexadecimal 
                = (digits + hexalpha).ToCharArray();
            DigitsAndAlphabet 
                = (digits + alpha + alpha.ToUpper()).ToCharArray();
        }
    }

    public static class RandomExtensions
    {
        public static string NextString(this Random random, 
            int length, char[] vocabulary)
        {
            if (random == null)
            {
                throw new ArgumentNullException();
            }

            if (vocabulary == null)
            {
                throw new ArgumentNullException("vocabulary");
            }

            if (length < 0)
            {
                throw new ArgumentOutOfRangeException("length",
                    "length must be positive.");
            }

            if (length == 0)
            {
                return String.Empty;
            }

            char[] chars = new char[length];

            while (--length >= 0)
            {
                var index = random.Next() % vocabulary.Length;

                chars[length] = vocabulary[index];
            }
            
            return new String(chars);
        }
    }
}
